from fastapi import Depends, Request
from afast_core.core_tools.jwt_helper import SimpleAuth
from infirmary_admin_src.infirmary_common.infirmary_errors.http_exception import SnowyPermissionDenied


async def smart_admin_check_login(request: Request) -> Request:
    # 免登入验证的API接口
    if request.url.path not in ["/adn/api/v1/auth/login",
                                "/adn/api/v1/auth/login/getCaptcha",
                                "/adn/api/v1/auth/login/logout",
                                # login/logout
                                "/docs", "/openapi.json"]:
        pass
        token = request.headers.get("X-Access-Token")
        if not token:
            raise SnowyPermissionDenied(message="当前没有访问权限！")

        isok, state, token_userinfo_result = SimpleAuth.verify_bearer_token_state(token=token)
        if not isok and (state == 1 or state == 2):
            raise SnowyPermissionDenied(message=token_userinfo_result)

        # 写入当前请求上下的当前对象
        request.state.token_userinfo_result = token_userinfo_result

        token = request.state.token_userinfo_result
        # 用户ID 写入上下文字

        # 写入相关的渠道编码ID
        request.state.login_name = token.get('login_name')
        request.state.employee_id = token.get('employee_id')
        request.state.administrator_flag = token.get('administrator_flag')
        request.state.department_code = token.get('department_code')

        return request
